﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.skype.api;
using System.Threading;
using System.Diagnostics;

namespace Hugo
{
    class Communicate
    {
        private String skypeAccountName;
        private String skypePassword;

        private static AppKeyPairMgr myAppKeyPairMgr = new AppKeyPairMgr();
        public static MySession mySession = new MySession();
        Contact[] myContactList;
        public static Participant activeParticipant;

        private static Communicate instance;

        public Contact getContactWithDisplayName(string s)
        {
            foreach (Contact c in myContactList)
            {
                if (c.getDisplayName().Equals(s))
                {
                    return c;
                }
            }
            return null;
        }


        public static Communicate getInstance()
        {
            if (instance == null)
            {
                instance = new Communicate();
            }

            return instance;
        }

        private Communicate()
        {
            setupSkype();
        }

        private void setupSkype()
        {
            String locationOfRuntime = GlobalSettings.SkypeRuntimePath;
            Process.Start(locationOfRuntime);

                // Update fonts
                this.skypeAccountName =  GlobalSettings.mySkypeID;
                this.skypePassword = GlobalSettings.mySkypePassword;
                        if (!myAppKeyPairMgr.isValidCertificate())
                            return;
                        mySession.doCreateSession(skypeAccountName, myAppKeyPairMgr.getPemFilePathname());
                        Console.WriteLine("Logging in ...");
                        if (mySession.mySignInMgr.Login(mySession, skypePassword))
                        {
                            //Console.WriteLine("You have logged in successfully");
                            //Thread.Sleep(SignInMgr.DELAY_INTERVAL);
                            doContacts(mySession);
                        }
                       
            return;
        }

        public Contact[] getContacts()
        {
            if (mySession != null && mySession.isLoggedIn())
            {
                Contact[]  contacts = mySession.mySkype.getHardwiredContactGroup(ContactGroup.Type.ALL_BUDDIES).getContacts();
                return contacts;
            }
            else
            {
                return null;
            }
        }

        public void sendMessage(String myCallTarget, String msg)
        {
            Console.WriteLine("MsgTarget : " + myCallTarget);
            String[] callTargets = { myCallTarget }; // Create & initialize the array in one step...
            Conversation myConversation =
                (Conversation)mySession.mySkype.getConversationByParticipants(callTargets, true, true);
            myConversation.postText(msg, false);
            Sounds.playSound(Sounds.Sound.Sent);
        }

        public void doMakeCall(String myCallTarget)
        {

            // Get available playback/recording devices; choose first of each
            if (mySession.setupAudioDevices(0, 1))
            {
                Console.WriteLine("Audio device set-up completed!");
            }
            else
            {
                Console.WriteLine("Audio device set-up failed - exiting!");
                return;
            }

            Console.WriteLine("CallTarget : " + myCallTarget);
            String[] callTargets = { myCallTarget }; // Create & initialize the array in one step...
            Conversation myConversation =
                (Conversation)mySession.mySkype.getConversationByParticipants(callTargets, true, true);

            Participant[] convParticipantList = myConversation.getParticipants(Conversation.ParticipantFilter.ALL);

            int i;
            Boolean callTargetFound = false;
            for (i = 0; i < convParticipantList.Length; i++)
            {
                if (convParticipantList[i].getIdentity().ToString() == myCallTarget)
                {
                    callTargetFound = true;
                    break;
                }
            }

            if (!callTargetFound)
            {
                Console.WriteLine("Could not find call target " + myCallTarget);
                return;
            }

            Console.WriteLine("Calling " + myCallTarget);	// Initiate the call
            mySession.callActive = true;
            //Console.WriteLine("B set callActive to " + Communicate.mySession.callActive);
            convParticipantList[i].ring(myCallTarget, false, 0, 10, false,
                                        mySession.myAccount.getSkypeName());
        }

        /*
        private void doChat() {
	
		    try {
			    while (true) {
				    int keyboardChar = System.in.read();
				    // Some platforms think ENTER is 0x0D; others think it's 0x0A...
				    if ((keyboardChar == 0x0D) || (keyboardChar == 0x0A)) {
					    break;
				    }
	   	   	    }
		    }
		    catch (IOException e) {
			    // TODO Auto-generated catch block
			    e.printStackTrace();
			    return;
		    }

		    // End capturing chat text
		    MySession.myConsole.println();
	    }
         */

        private void doContacts(MySession mySession)
        {
            myContactList = mySession.mySkype.getHardwiredContactGroup(ContactGroup.Type.ALL_BUDDIES).getContacts();

            Console.WriteLine("Your contact list");
            foreach (Contact c in myContactList)
            {
                Console.WriteLine("\t" + c.getDisplayName());
                //Console.WriteLine(c.getAbout());
            }
        }
        
        private void doMakeCall(MySession mySession, String myCallTarget)
        {

            // Get available playback/recording devices; choose first of each
            if (mySession.setupAudioDevices(0, 1))
            {
                Console.WriteLine("Audio device set-up completed!");
            }
            else
            {
                Console.WriteLine("Audio device set-up failed - exiting!");
                return;
            }

            Console.WriteLine("CallTarget : " + myCallTarget);
            String[] callTargets = { myCallTarget }; // Create & initialize the array in one step...
            Conversation myConversation =
                (Conversation)mySession.mySkype.getConversationByParticipants(callTargets, true, true);

            Participant[] convParticipantList = myConversation.getParticipants(Conversation.ParticipantFilter.ALL);

            int i;
            Boolean callTargetFound = false;
            for (i = 0; i < convParticipantList.Length; i++)
            {
                if (convParticipantList[i].getIdentity().ToString() == myCallTarget)
                {
                    callTargetFound = true;
                    break;
                }
            }

            if (!callTargetFound)
            {
                Console.WriteLine("Could not find call target " + myCallTarget);
                return;
            }

            Console.WriteLine("Calling " + myCallTarget);	// Initiate the call
            mySession.callActive = true;
            //Console.WriteLine("C set callActive to " + Communicate.mySession.callActive);
            activeParticipant = convParticipantList[i];
            activeParticipant.ring(myCallTarget, false, 0, 10, false,
                                        mySession.myAccount.getSkypeName());

            // Loop until the call finishes
            while (mySession.callActive)
            {
                try
                {
                    Thread.Sleep(SignInMgr.DELAY_INTERVAL);
                }
                catch (Exception e)
                {
                    // TODO Auto-generated catch block
                    Console.WriteLine(e.StackTrace);
                    return;
                }
            }
        }
    }
}
